package edu.vt.ece.rt.quorum.messsages.types;

import org.jgroups.Address;

import edu.vt.ece.rt.dstm.Context;
import edu.vt.ece.rt.dstm.QObject;
import edu.vt.ece.rt.quorum.Cluster;
import edu.vt.ece.rt.quorum.ClustersManager;
import edu.vt.ece.rt.quorum.Resource;
import edu.vt.ece.rt.quorum.messsages.QMessage;
import edu.vt.ece.rt.quorum.messsages.QMessage.MessageType;
import edu.vt.ece.rt.quorum.util.Names;

/*
 * Message to node to join the Cluster
 * @author Sudhanshu
 */

public class JoinCluster extends QMessage implements Runnable {
	String name;				//Name of cluster of join on node
	Boolean done;

	public JoinCluster(String n) {
		super(MessageType.JoinCluster);
		name = n;
		done = false;
	}
	
	public JoinCluster(String n, Boolean finished) {
		super(MessageType.JoinCluster);
		name = n;
		done = finished;
	}
	
	@Override
	public void run() {
		if (!done) {
			Cluster c = new Cluster(name);
			try {
				c.init();
			} catch (Exception e) {
				e.printStackTrace();
			}
			ClustersManager.registerCluster(name, c);
		} else {
			synchronized(Resource.waitObj){
				Resource.nodesFinished++;
				if (Resource.nodesFinished == (Integer.getInteger(Names.nodes) - 1)) {
					Resource.waitObj.notify();
				}
			}
		}
	}	
}
